package distributed

import (
	"context"
	"encoding/json"
	client "go.etcd.io/etcd/client/v3"
	"log"
	"time"
)

var configPath = `/configs/remote_config.json`
var kapi, _ = client.New(client.Config{
	Endpoints:   []string{"http://127.0.0.1:2379"},
	DialTimeout: 5 * time.Second,
})

var appConfig ConfigStruct

//func init() {
//	cfg := client.Config{
//		Endpoints:               []string{"http://127.0.0.1:2379"},
//		Transport:               client.DefaultTransport,
//		HeaderTimeoutPerRequest: time.Second,
//	}
//
//	c, err := client.New(cfg)
//	if err != nil {
//		log.Fatal(err)
//	}
//	kapi = client.NewKeysAPI(c)
//	initConfig()
//}

func watchAndUpdate() {
	go func() {
		// watch 该节点下的每次变化
		for {
			select {
			case resp := <-kapi.Watcher.Watch(context.Background(), configPath, nil):
				log.Println("new values is ", string(resp.Events[0].Kv.Value))

				err := json.Unmarshal(resp.Events[0].Kv.Value, &appConfig)
				if err != nil {
					log.Fatal(err)
				}
			}
		}
	}()
}

func initConfig() {
	resp, err := kapi.Get(context.Background(), configPath, nil)
	if err != nil {
		log.Fatal(err)
	}

	err = json.Unmarshal(resp.Kvs[0].Value, &appConfig)
	if err != nil {
		log.Fatal(err)
	}
}

func getConfig() ConfigStruct {
	return appConfig
}

type ConfigStruct struct {
	Addr           string `json:"addr"`
	AesKey         string `json:"aes_key"`
	HTTPS          bool   `json:"https"`
	Secret         string `json:"secret"`
	PrivateKeyPath string `json:"private_key_path"`
	CertFilePath   string `json:"cert_file_path"`
}

func EtcdConfig() {
	// init your app
}
